package fr.obsmip.sedoo.client.activity;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import fr.obsmip.sedoo.client.ClientFactory;
import fr.obsmip.sedoo.client.Constants;
import fr.obsmip.sedoo.client.ShortcutFactory;
import fr.obsmip.sedoo.client.event.ActionEventConstant;
import fr.obsmip.sedoo.client.message.Message;
import fr.obsmip.sedoo.client.place.DatasetEditingPlace;
import fr.obsmip.sedoo.client.place.ExperimentalSiteEditingPlace;
import fr.obsmip.sedoo.client.place.ExperimentalSiteEntryCreationPlace;
import fr.obsmip.sedoo.client.service.MetadataService;
import fr.obsmip.sedoo.client.service.MetadataServiceAsync;
import fr.obsmip.sedoo.client.ui.ExperimentalSiteEntryView;
import fr.obsmip.sedoo.client.ui.ExperimentalSiteEntryView.ExperimentalSiteEntryPresenter;
import fr.obsmip.sedoo.client.ui.misc.BreadCrumb;
import fr.obsmip.sedoo.client.ui.misc.Shortcut;
import fr.obsmip.sedoo.client.ui.table.ObservatoryPersonTable;
import fr.obsmip.sedoo.shared.domain.ExperimentalSiteDTO;
import fr.sedoo.commons.client.event.ActionStartEvent;
import fr.sedoo.commons.client.event.NotificationEvent;
import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.service.DefaultAbstractCallBack;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.client.widget.DialogBoxTools;
import fr.sedoo.commons.client.widget.editing.ValidationAlert;
import fr.sedoo.metadata.shared.domain.MetadataDTO;
import fr.sedoo.metadata.shared.domain.MetadataSummaryDTO;
import fr.sedoo.metadata.shared.domain.dto.I18nString;

public class ExperimentalSiteEntryEditingActivity extends AbstractMetadataEditingActivity implements ExperimentalSiteEntryPresenter {

	private String experimentalSiteUuid;
	private String experimentalSiteName;
	private MetadataSummaryDTO observatorySummary;
	private String mode;

	public ExperimentalSiteEntryEditingActivity(ExperimentalSiteEditingPlace place, ClientFactory clientFactory) {
		super(clientFactory, place);
		if (StringUtil.isNotEmpty(place.getExperimentalSiteUuid()))
		{
			experimentalSiteUuid = place.getExperimentalSiteUuid();
			mode = Constants.MODIFY;
		}
		else
		{
			experimentalSiteName = place.getExperimentalSiteName();
			observatorySummary = place.getParentSummary();
			mode = Constants.CREATE;
		}
	}

	private static final MetadataServiceAsync METADATA_SERVICE = GWT.create(MetadataService.class);

	@Override
	public void start(final AcceptsOneWidget containerWidget, EventBus eventBus) {

		if (isValidUser() == false)
		{
			goToLoginPlace();
			return;
		}
		if (mode.compareTo(Constants.CREATE)==0)
		{
			if (observatorySummary == null)
			{
				clientFactory.getPlaceController().goTo(new ExperimentalSiteEntryCreationPlace());
				return;
			}
		}
		sendActivityStartEvent();
		containerWidget.setWidget(clientFactory.getProgressView());
		if (mode.compareTo(Constants.CREATE)==0)
		{
			ActionStartEvent startEvent = new ActionStartEvent(CommonMessages.INSTANCE.refreshing(), ActionEventConstant.REFRESHING, true);
			clientFactory.getEventBus().fireEvent(startEvent);
			broadcastActivityTitle(Message.INSTANCE.experimentalSiteEditingViewCreationHeader());
			
			previousHash="";
			ExperimentalSiteDTO newExperimentalSite = clientFactory.createExperimentalSiteDTO(experimentalSiteName, observatorySummary);
			view = clientFactory.getExperimentalSiteEntryEditingView();
			((ExperimentalSiteEntryView) view).setPresenter(this);
			containerWidget.setWidget(view.asWidget());
			view.edit(newExperimentalSite);
			clientFactory.getEventBus().fireEvent(startEvent.getEndingEvent());
		}
		else
		{
			broadcastActivityTitle(Message.INSTANCE.experimentalSiteEditingViewModificationHeader());
			final ActionStartEvent startEvent = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstant.EXPERIMENTAL_SITE_LOADING_EVENT, true);
			clientFactory.getEventBus().fireEvent(startEvent);
			METADATA_SERVICE.getExperimentalSiteByUuid(experimentalSiteUuid, clientFactory.getMetadataLanguages(), new DefaultAbstractCallBack<ExperimentalSiteDTO>(startEvent, clientFactory.getEventBus()) {

				@Override
				public void onSuccess(ExperimentalSiteDTO result) {
					super.onSuccess(result);
					observatorySummary = result.getParentSummary();
					view = clientFactory.getExperimentalSiteEntryEditingView();
					((ExperimentalSiteEntryView) view).setPresenter(ExperimentalSiteEntryEditingActivity.this);
					containerWidget.setWidget(view.asWidget());
					previousHash = result.getHash();
					view.edit(result);
					clientFactory.getEventBus().fireEvent(startEvent.getEndingEvent());
					clientFactory.getBreadCrumb().addShortcut(ShortcutFactory.getExperimentalSiteModificationShortcut(result.getExperimentalSiteName(), experimentalSiteUuid));
				}

			});
		}

	}
	
	
	private void traceHash(ExperimentalSiteDTO dto) {
		
	}


	@Override
	public void save(final MetadataDTO experimentalSiteDTO) 
	{
		List<ValidationAlert> validationResult = experimentalSiteDTO.validate();
		if (validationResult.isEmpty() == false)
		{
			DialogBoxTools.popUpScrollable(CommonMessages.INSTANCE.error(), ValidationAlert.toHTML(validationResult), DialogBoxTools.HTML_MODE);
			return;
		}
		else
		{

			ActionStartEvent startEvent = new ActionStartEvent(Message.INSTANCE.saving(), ActionEventConstant.EXPERIMENTAL_SITE_SAVING_EVENT, true);
			clientFactory.getEventBus().fireEvent(startEvent);
			ExperimentalSiteDTO aux = (ExperimentalSiteDTO) experimentalSiteDTO;
			METADATA_SERVICE.saveExperimentalSite(experimentalSiteDTO, aux.getParentSummary().getName(), clientFactory.getMetadataLanguages(), new DefaultAbstractCallBack<MetadataDTO>(startEvent, clientFactory.getEventBus()) {

				@Override
				public void onSuccess(MetadataDTO result) {
					super.onSuccess(result);
					clientFactory.getEventBus().fireEvent(new NotificationEvent(Message.INSTANCE.savedModifications()));
					ActionStartEvent refreshEvent = new ActionStartEvent(CommonMessages.INSTANCE.refreshing(), ActionEventConstant.REFRESHING_EVENT, true);
					clientFactory.getEventBus().fireEvent(refreshEvent);
					view.edit(result);
					clientFactory.getEventBus().fireEvent(refreshEvent.getEndingEvent());
					previousHash = result.getHash();
					if (mode.compareTo(Constants.CREATE)==0)
					{
						experimentalSiteUuid = result.getOtherPart().getUuid();
						setMode(Constants.MODIFY);
						broadcastActivityTitle(Message.INSTANCE.experimentalSiteEditingViewModificationHeader());
						clientFactory.getBreadCrumb().addShortcut(ShortcutFactory.getExperimentalSiteModificationShortcut(((ExperimentalSiteDTO) result).getExperimentalSiteName(), experimentalSiteUuid));
					}
				}
			});
		}
	}


	@Override
	public void back() {
		traceHash((ExperimentalSiteDTO) view.flush());
		BreadCrumb breadCrumb = clientFactory.getBreadCrumb();
		List<Shortcut> shortcuts = breadCrumb.getShortcuts();
		if ((shortcuts != null) && (shortcuts.size()>1))
		{
			Shortcut shortcut = shortcuts.get(shortcuts.size() - 2);
			clientFactory.getPlaceController().goTo(shortcut.getPlace());
		}

	}


	@Override
	public void generateXML(MetadataDTO metadataDTO) {
		// TODO Auto-generated method stub

	}


	@Override
	public void validate(MetadataDTO dto) {
		List<ValidationAlert> validationResult = dto.validate();
		if (validationResult.isEmpty() == false)
		{
			DialogBoxTools.popUpScrollable(CommonMessages.INSTANCE.error(), ValidationAlert.toHTML(validationResult), DialogBoxTools.HTML_MODE);
			return;
		}
		else
		{
			DialogBoxTools.modalAlert(CommonMessages.INSTANCE.information(), Message.INSTANCE.noValidationProblems());
		}

	}

	
	@Override
	public void print(String uuid) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void xml(String uuid) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void deleteDataset(final String uuid) {
		final ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.deleting(), ActionEventConstant.DATASET_DELETING_EVENT, true);
		clientFactory.getEventBus().fireEvent(e);
		METADATA_SERVICE.deleteObservatoryEntry(uuid, new DefaultAbstractCallBack<Boolean>(e, clientFactory.getEventBus()) 
		{
			@Override
			public void onSuccess(Boolean result) {
				super.onSuccess(result);
				clientFactory.getEventBus().fireEvent(new NotificationEvent(CommonMessages.INSTANCE.deletedElement()));
				((ExperimentalSiteEntryView) view).broadcastExperimentalSiteDeletion(uuid);
			}
		});
		
	}


	@Override
	public void goToDatasetEditPlace(MetadataSummaryDTO hasId) {
		DatasetEditingPlace place = new DatasetEditingPlace();
		place.setDatasetUuid(hasId.getIdentifier());
		clientFactory.getPlaceController().goTo(place);
	}


	@Override
	public void addDataset() {
		if (isDirty())
		{
			DialogBoxTools.modalAlert(CommonMessages.INSTANCE.information(), Message.INSTANCE.saveExperimentalSiteFirst());
		}
		else
		{
						
			ExperimentalSiteDTO experimentalSite = (ExperimentalSiteDTO) view.flush();
			DatasetEditingPlace place = new DatasetEditingPlace();
			place.setObservatorySummary(observatorySummary);
			MetadataSummaryDTO experimentalSiteSummary = new MetadataSummaryDTO();
			experimentalSiteSummary.setUuid(experimentalSite.getOtherPart().getUuid());
			experimentalSiteSummary.setName(experimentalSite.getExperimentalSiteName());
			place.setExperimentalSiteSummary(experimentalSiteSummary);
			clientFactory.getPlaceController().goTo(place);
		}
		
	}


	@Override
	public void getParentUseConditions() 
	{
		final ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstant.BASIC_LOADING_EVENT, true);
		clientFactory.getEventBus().fireEvent(e);
		METADATA_SERVICE.computeUseConditionsFromParent(observatorySummary.getUuid(), clientFactory.getDisplayLanguages(), new DefaultAbstractCallBack<I18nString>(e, clientFactory.getEventBus()) 
		{
			@Override
			public void onSuccess(I18nString result) {
				super.onSuccess(result);
				((ExperimentalSiteEntryView) view).setUseConditions(result);
			}
		});
	}


	@Override
	public void getParentPublicAccessLimitations() {
		final ActionStartEvent e = new ActionStartEvent(CommonMessages.INSTANCE.loading(), ActionEventConstant.BASIC_LOADING_EVENT, true);
		clientFactory.getEventBus().fireEvent(e);
		METADATA_SERVICE.computePublicAccessLimitationsFromParent(observatorySummary.getUuid(), clientFactory.getDisplayLanguages(), new DefaultAbstractCallBack<I18nString>(e, clientFactory.getEventBus()) 
		{
			@Override
			public void onSuccess(I18nString result) {
				super.onSuccess(result);
				((ExperimentalSiteEntryView) view).setPublicAccessLimitations(result);
			}
		});		
	}


	@Override
	public String getObservatoryName() 
	{
		return observatorySummary.getName();
	}


	@Override
	public void loadDirectoryPersons(ObservatoryPersonTable table) {
		loadDirectoryPersonsByObservatoryName(getObservatoryName(), table);
		
	}





}
